﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SQLServerHealthCheck.Model;
using AG.Utilities;

namespace SQLServerHealthCheck.SQLServer.IssueTypes
{
    class UnevenFileGrowthSettingsinOneFilegroup : IssueTypeCheckBase
    {
        public UnevenFileGrowthSettingsinOneFilegroup()
        {
            IssueTypeId = 3022;
        }
        public override void Check()
        {
            try
            {
                HealthCheckDataContext dc = new HealthCheckDataContext(System.Configuration.ConfigurationManager.AppSettings["ConnectionStringSSHCDatabase"]);
                Issue issue;
                ThresholdValue thresholdValue = dc.ThresholdValues.FirstOrDefault(t => t.IssueTypeID == IssueTypeId && t.ThresholdValueID == 1);
                var ServerQry = from d in dc.Databases
                                from df in d.DatabaseFiles

                                where df.FileGroup != "LOG"
                                && (d.DatabaseName != "distribution") && (d.DatabaseName != "master") && (d.DatabaseName != "msdb")
                                && d.SourceDatabaseId == null
                                group df by new { df.DatabaseID, df.Database.DatabaseName } into groupGrowthPercent
                                select new
                                {
                                    databaseID = groupGrowthPercent.Key.DatabaseID,
                                    CountPercent = groupGrowthPercent.Select(x => x.GrowthPercent).Distinct().Count(),
                                    CountMb = groupGrowthPercent.Select(x => x.GrowthMegaBytes).Distinct().Count(),
                                    DatabaseName = groupGrowthPercent.Key.DatabaseName
                                };
                //Get Issuetype object  And Create a new  Global issue object 

                IssueType issueType = dc.IssueTypes.FirstOrDefault(i => i.IssueTypeId == IssueTypeId);

                foreach (var item in ServerQry)
                {
                    //Get Issuetype object
                    if ((item.CountPercent > 1) || (item.CountMb > 1))
                    {
                        issue = new Issue();

                        issue.IssueType = issueType;
                        issue.TargetId = item.databaseID;
                        issue.Description = issueType.Description.Replace("{Database}", item.DatabaseName);

                        dc.Issues.InsertOnSubmit(issue);
                    }
                }

                dc.SubmitChanges();

            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }
        }
    }
}
